package com.example.webrtcdemo

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.webrtcdemo.webrtc.SignalingClient
import com.example.webrtcdemo.webrtc.WebRtcManager
import com.permissionx.guolindev.PermissionX
import org.webrtc.AudioTrack
import org.webrtc.MediaStream
import org.webrtc.PeerConnection
import org.webrtc.SurfaceViewRenderer
import org.webrtc.VideoTrack

class MainActivity : AppCompatActivity() , WebRtcManager.WebRtcListener{
    private val TAG = "MainActivity"

    // UI组件
    private lateinit var localVideoView: SurfaceViewRenderer
    private lateinit var remoteVideoView: SurfaceViewRenderer
    private lateinit var btnStartCall: Button
    private lateinit var btnEndCall: Button
    private lateinit var btnSendMessage: Button
    private lateinit var etRemoteUserId: EditText
    private lateinit var etMessage: EditText
    private lateinit var tvStatus: TextView
    private lateinit var tvMessages: TextView

    // WebRTC管理器
    private lateinit var webRtcManager: WebRtcManager
    private lateinit var signalingClient: SignalingClient

    // 配置
    private val localUserId = "user_${System.currentTimeMillis() % 10000}"
    private val signalingServerUrl = "wss://iot-test.petgugu.com/ws?platform=android&user_id=10000&target=app&version=10001&sdkver=100" // 替换为你的信令服务器地址

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initViews()
        requestPermissions()
    }

    private fun initViews() {
        localVideoView = findViewById(R.id.local_video_view)
        remoteVideoView = findViewById(R.id.remote_video_view)
        btnStartCall = findViewById(R.id.btn_start_call)
        btnEndCall = findViewById(R.id.btn_end_call)
        btnSendMessage = findViewById(R.id.btn_send_message)
        etRemoteUserId = findViewById(R.id.et_remote_user_id)
        etMessage = findViewById(R.id.et_message)
        tvStatus = findViewById(R.id.tv_status)
        tvMessages = findViewById(R.id.tv_messages)

        // 设置按钮点击事件
        btnStartCall.setOnClickListener { startCall() }
        btnEndCall.setOnClickListener { endCall() }
        btnSendMessage.setOnClickListener { sendMessage() }

        updateStatus("应用已启动，本地用户ID: $localUserId")
    }

    private fun requestPermissions() {
        PermissionX.init(this)
            .permissions(
                android.Manifest.permission.CAMERA,
                android.Manifest.permission.RECORD_AUDIO,
                android.Manifest.permission.MODIFY_AUDIO_SETTINGS
            )
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(
                    deniedList,
                    "需要摄像头和麦克风权限以实现视频通话功能",
                    "确定",
                    "取消"
                )
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    initWebRTC()
                    updateStatus("权限获取成功，准备就绪")
                } else {
                    updateStatus("权限被拒绝，无法使用视频通话功能")
                    Toast.makeText(this, "部分权限被拒绝", Toast.LENGTH_LONG).show()
                }
            }
    }

    private fun initWebRTC() {
        try {
            // 初始化信令客户端
            signalingClient = SignalingClient(signalingServerUrl, localUserId)
            val turnConfig = WebRtcManager.TurnServerConfig(
                turnUrl = "turn:120.79.206.28:3478",
                username = "admin",
                //username = "82y2wdnhsLVwVIHwT",
                password = "qaz123456"
               // password = "k4a64tuF61vvpc5j1N9XMfmDpr01"
            )
            // 初始化WebRTC管理器
            webRtcManager = WebRtcManager(
                context = this,
                signalingClient = signalingClient,
                localVideoView = localVideoView,
                remoteVideoView = remoteVideoView,
                remoteUserId = "10026e957788",
                turnConfig = turnConfig
            )
            webRtcManager.setListener(this)

            // 连接信令服务器
            signalingClient.connect()

            updateStatus("WebRTC初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "WebRTC初始化失败", e)
            updateStatus("WebRTC初始化失败: ${e.message}")
        }
    }

    private fun startCall() {
        val remoteUserId = "10026e957788"
        if (remoteUserId.isEmpty()) {
            Toast.makeText(this, "请输入对方用户ID", Toast.LENGTH_SHORT).show()
            return
        }

        updateStatus("正在呼叫用户: $remoteUserId")

        // 设置目标用户ID并开始呼叫
        webRtcManager.setRemoteUserId(remoteUserId)
        webRtcManager.createAndSendOffer()
    }

    private fun endCall() {
        webRtcManager.disconnect()
        updateStatus("通话已结束")
        appendMessage("系统: 通话结束")
    }

    private fun sendMessage() {
        val message = etMessage.text.toString().trim()
        if (message.isEmpty()) {
            Toast.makeText(this, "请输入消息内容", Toast.LENGTH_SHORT).show()
            return
        }

        webRtcManager.sendP2PMessage(message) { success, error ->
            runOnUiThread {
                if (success) {
                    appendMessage("我: $message")
                    etMessage.setText("")
                } else {
                    Toast.makeText(this, "消息发送失败: $error", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateStatus(status: String) {
        runOnUiThread {
            tvStatus.text = "状态: $status"
            Log.d(TAG, status)
        }
    }

    private fun appendMessage(message: String) {
        runOnUiThread {
            val currentText = tvMessages.text.toString()
            tvMessages.text = if (currentText.isEmpty()) {
                message
            } else {
                "$currentText\n$message"
            }
        }
    }

    // WebRTC 回调实现
    override fun onInitialized() {
        updateStatus("WebRTC初始化完成")
    }

    override fun onSignalingConnected() {
        updateStatus("信令服务器连接成功")
    }

    override fun onConnected() {
        updateStatus("P2P连接建立成功")
        appendMessage("系统: 通话连接成功")
    }

    override fun onCompleted() {
        updateStatus("P2P连接完成")
    }

    override fun onDisconnected() {
        updateStatus("连接断开")
        appendMessage("系统: 连接断开")
    }

    override fun onDataChannelConnected() {
        updateStatus("数据通道连接成功")
        appendMessage("系统: 可以发送文本消息了")
    }

    override fun onMessageReceived(message: String) {
        appendMessage("对方: $message")
    }

    override fun onConnectionStateChange(state: PeerConnection.IceConnectionState) {
        updateStatus("连接状态: $state")
    }

    override fun onSignalingStateChange(state: PeerConnection.SignalingState) {
        Log.d(TAG, "信令状态: $state")
    }

    override fun onIceGatheringStateChange(state: PeerConnection.IceGatheringState) {
        Log.d(TAG, "ICE收集状态: $state")
    }

    override fun onRemoteStreamAdded(stream: MediaStream) {
        updateStatus("收到远程视频流")
    }

    override fun onRemoteStreamRemoved(stream: MediaStream) {
        updateStatus("远程视频流断开")
    }

    override fun onRemoteVideoTrackAdded(track: VideoTrack) {
        Log.d(TAG, "远程视频轨道添加")
    }

    override fun onRemoteAudioTrackAdded(track: AudioTrack) {
        Log.d(TAG, "远程音频轨道添加")
    }

    override fun onRenegotiationNeeded() {
        Log.d(TAG, "需要重新协商")
    }

    override fun onError(message: String) {
        updateStatus("错误: $message")
        appendMessage("系统错误: $message")
        val handler = Handler(Looper.getMainLooper())
        handler.post {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        webRtcManager.disconnect()
    }
}